package com.robot.agent.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.robot.agent.client.MemberClient;
import com.robot.agent.pojo.Agent;
import com.robot.agent.pojo.client.MerchantApply;
import com.robot.agent.service.AgentService;
import entity.Result;
import entity.StatusCode;
import io.jsonwebtoken.Claims;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.time.LocalDateTime;
import java.util.Map;

/**
 * @author wuyunbin
 */
@RestController
@CrossOrigin
@RequestMapping("/agent")
public class MerchantApplyController {
    private final Logger logger = LoggerFactory.getLogger(this.getClass());

    @Autowired
    private MemberClient memberClient;

    @Autowired
    private HttpServletRequest request;

    @Autowired
    private AgentService agentService;

    /**
     * merchant_apply表status状态 0-初审待审核 1-初审通过 2-初审失败 3-平台待审核 4-平台审核通过 5-平台审核失败
     */
    private String merchantApplyStatusFirstTrial = "0";
    private String merchantApplyStatusFirstTrialSuccess = "1";
    private String merchantApplyStatusFirstTrialFailed = "2";
    private String merchantApplyStatusSecondTrial = "3";
    private String merchantApplyStatusSecondTrialSuccess = "4";
    private String merchantApplyStatusSecondTrialFailed = "5";

    /**
     * store表type 商户类型 0-充送 1-折扣
     */
    private String storeTypeZero = "0";
    private String storeTypeOne = "1";
    /**
     * store表account_type 账户类型 0-对私 1-对公
     */
    private String storeAccountTypeZero = "0";
    private String storeAccountTypeOne = "1";


    /**
     * 所有商户入驻申请
     *
     * @return
     */
    @PostMapping("applications/{page}/{size}")
    public Result findApplications(@RequestBody Map searchMap, @PathVariable int page, @PathVariable int size) {
        Claims claims = (Claims) request.getAttribute("robot_agent");
        if (claims == null) {
            return new Result(StatusCode.ERROR_TOKEN_EXPIRED);
        }
        logger.info("claims.getId()=" + claims.getId() + ";searchMap=" + searchMap);

        Agent agentInDb = agentService.findById(claims.getId());
        logger.info("agentInDb=" + agentInDb);
        //前端调用findByToken接口检查过了,所以这里不再对代理商是否存在和状态进行判断

        searchMap.put("areaId", agentInDb.getAreaId());
        JSONObject jsonObject = JSON.parseObject(memberClient.thirdFindMerchantAppliesBySearch(searchMap, page, size));
        return new Result(StatusCode.SUCCESS_QUERY, jsonObject);
    }

    /**
     * 某一入驻申请
     *
     * @param id
     * @return
     */
    @GetMapping("application/{id}")
    public Result findApplication(@PathVariable String id) {
        Claims claims = (Claims) request.getAttribute("robot_agent");
        if (claims == null) {
            return new Result(StatusCode.ERROR_TOKEN_EXPIRED);
        }
        logger.info("claims.getId()=" + claims.getId());

        MerchantApply merchantApplyInDb = JSON.parseObject(memberClient.thirdFindMerchantApplyById(id), MerchantApply.class);
        logger.info("merchantApplyInDb=" + merchantApplyInDb);
        String message = checkPojo(merchantApplyInDb);
        if (!"".equals(message)) {
            return new Result(StatusCode.ERROR, message);
        }

        return new Result(StatusCode.SUCCESS_QUERY, merchantApplyInDb);
    }

    /**
     * 更新入驻申请审核状态 0-初审待审核 1-初审通过 2-平台审核失败 3-平台待审核 4-平台审核通过 5-平台审核失败
     *
     * @param id
     * @param status
     * @return
     */
    @PutMapping("application/firstTrial/{status}/{id}")
    @Transactional(rollbackFor = Exception.class)
    public Result firstTrial(@RequestBody MerchantApply merchantApply, @PathVariable String status, @PathVariable String id) {
        Claims claims = (Claims) request.getAttribute("robot_agent");
        if (claims == null) {
            return new Result(StatusCode.ERROR_TOKEN_EXPIRED);
        }
        logger.info("claims.getId()=" + claims.getId());

        Agent agentInDb = agentService.findById(claims.getId());
        logger.info("agentInDb=" + agentInDb);
        //前端调用findByToken接口检查过了,所以这里不再对代理商是否存在和状态进行判断

        if (merchantApplyStatusFirstTrialFailed.equals(status) || merchantApplyStatusFirstTrialSuccess.equals(status)) {
            MerchantApply merchantApplyInDb = JSON.parseObject(memberClient.thirdFindMerchantApplyById(id), MerchantApply.class);
            logger.info("merchantApplyInDb=" + merchantApplyInDb);
            if (merchantApplyInDb == null || merchantApplyInDb.getDeletedAt() != null) {
                return new Result(StatusCode.ERROR_RECORD_DOES_NOTE_EXIST);
            }
            if (!agentInDb.getArea().equals(merchantApplyInDb.getArea()) || !agentInDb.getAreaId().equals(merchantApplyInDb.getAreaId())) {
                return new Result(StatusCode.ERROR_AGENT_AREA_INVALID);
            }
            if (merchantApplyStatusFirstTrialSuccess.equals(merchantApplyInDb.getStatus())) {
                return new Result(StatusCode.ERROR_AGENT_STATUS_INVALID);
            }
            if (merchantApplyStatusSecondTrialSuccess.equals(merchantApplyInDb.getStatus())) {
                return new Result(StatusCode.ERROR_AGENT_EXEC_FAIL);
            }
            if (merchantApplyStatusFirstTrialFailed.equals(status)) {
                if (merchantApply.getRemark() == null || "".equals(merchantApply.getRemark())) {
                    return new Result(StatusCode.ERROR_AGENT_REMARK_REQUIRED);
                }
                logger.info("remark=" + merchantApply.getRemark());
                merchantApplyInDb.setRemark(merchantApply.getRemark());
            }
            merchantApplyInDb.setStatus(status);
            memberClient.thirdUpdateMerchantApply(JSON.toJSONString(merchantApplyInDb));
            logger.info("status" + status);
        } else {
            return new Result(StatusCode.ERROR, "审核状态错误");
        }
        return new Result(StatusCode.SUCCESS);
    }

    /**
     * 代理商补充商家信息,此时还不是商家
     *
     * @param id
     * @return
     */
    @PutMapping("application/updateStore/{id}")
    @Transactional(rollbackFor = Exception.class)
    public Result updateStore(@PathVariable String id, @RequestBody Map<String, Object> map) {
        logger.info("map=" + map);
        //检查代理商
        Claims claims = (Claims) request.getAttribute("robot_agent");
        if (claims == null) {
            return new Result(StatusCode.ERROR_TOKEN_EXPIRED);
        }
        logger.info("claims.getId()=" + claims.getId());

        Agent agentInDb = agentService.findById(claims.getId());
        logger.info("agentInDb=" + agentInDb);
        //前端调用findByToken接口检查过了,所以这里不再对代理商是否存在和状态进行判断

        //获取商家申请
        MerchantApply merchantApplyInDb = JSON.parseObject(memberClient.thirdFindMerchantApplyById(id), MerchantApply.class);
        logger.info("merchantApplyInDb=" + merchantApplyInDb);
        if (merchantApplyInDb == null || merchantApplyInDb.getDeletedAt() != null) {
            return new Result(StatusCode.ERROR_RECORD_DOES_NOTE_EXIST);
        }
        if (!agentInDb.getArea().equals(merchantApplyInDb.getArea()) || !agentInDb.getAreaId().equals(merchantApplyInDb.getAreaId())) {
            return new Result(StatusCode.ERROR_AGENT_AREA_INVALID);
        }
        if (merchantApplyStatusSecondTrialSuccess.equals(merchantApplyInDb.getStatus())) {
            return new Result(StatusCode.ERROR_AGENT_EXEC_FAIL);
        }


        String type = "type";
        if (map.get(type) == null || "".equals(map.get(type))) {
            return new Result(StatusCode.ERROR_MERCHANT_TYPE_REQUIRED);
        } else if ((!storeTypeZero.equals(map.get(type)) && !storeTypeOne.equals(map.get(type)))) {
            return new Result(StatusCode.ERROR_MERCHANT_TYPE_INVALID);
        }


        String vip1 = "vip1";
        if (map.get(vip1) == null || "".equals(map.get(vip1))) {
            return new Result(StatusCode.ERROR_RATE_REQUIRED);
        }
        String vip2 = "vip2";
        if (map.get(vip2) == null || "".equals(map.get(vip2))) {
            return new Result(StatusCode.ERROR_PLUS_RATE_REQUIRED);
        }
        String rate = "{\"vip1\":\"" + map.get(vip1) + "\",\"vip2\":\"" + map.get(vip2) + "\"}";
        String creditString = "credit";
        if (map.get(creditString) != null) {
            Double credit = Double.valueOf((String) map.get(creditString));
            merchantApplyInDb.setCredit(credit);
        }

        String bankName = "bankName";

        String bankAccount = "bankAccount";

        String accountName = "accountName";

        String accountType = "accountType";

        merchantApplyInDb.setType((String) map.get(type));
        merchantApplyInDb.setRate(rate);
        merchantApplyInDb.setBankName((String) map.get(bankName));
        merchantApplyInDb.setBankAccount((String) map.get(bankAccount));
        merchantApplyInDb.setAccountName((String) map.get(accountName));
        Object obj = map.get(accountType);
        merchantApplyInDb.setAccountType((String) map.get(accountType));
        //字段补全才设为平台待审核
        if (invalidFieldsNotNull(merchantApplyInDb)) {
            logger.info("字段补全才设为平台待审核");
            merchantApplyInDb.setStatus(merchantApplyStatusSecondTrial);
        }
        merchantApplyInDb.setUpdatedAt(LocalDateTime.now());
        memberClient.thirdUpdateMerchantApply(JSON.toJSONString(merchantApplyInDb));
        return new Result(StatusCode.SUCCESS);
    }

    /**
     * 软删除某一入驻申请
     *
     * @param id
     * @return
     */
    @DeleteMapping("application/{id}")
    @Transactional(rollbackFor = Exception.class)
    public Result deleteApplication(@PathVariable String id) {
        Claims claims = (Claims) request.getAttribute("robot_agent");
        if (claims == null) {
            return new Result(StatusCode.ERROR_TOKEN_EXPIRED);
        }
        logger.info("claims.getId()=" + claims.getId() + ";id=" + id);
        Agent agentInDb = agentService.findById(claims.getId());
        logger.info("agentInDb=" + agentInDb);
        //前端调用findByToken接口检查过了,所以这里不再对代理商是否存在和状态进行判断

        MerchantApply merchantApplyInDb = JSON.parseObject(memberClient.thirdFindMerchantApplyById(id), MerchantApply.class);
        logger.info("merchantApplyInDb=" + merchantApplyInDb);
        if (merchantApplyInDb == null) {
            return new Result(StatusCode.ERROR_RECORD_DOES_NOTE_EXIST);
        }
        if (!agentInDb.getAreaId().equals(merchantApplyInDb.getAreaId())) {
            return new Result(StatusCode.ERROR_AGENT_AREA_INVALID);
        }
        merchantApplyInDb.setDeletedAt(LocalDateTime.now());
        memberClient.thirdUpdateMerchantApply(JSON.toJSONString(merchantApplyInDb));
        return new Result(StatusCode.SUCCESS_DELETED);
    }

    /**
     * 检验是否字段补全
     *
     * @param merchantApply
     * @return
     */
    public boolean invalidFieldsNotNull(MerchantApply merchantApply) {
        //店铺/商家名字
        if (merchantApply.getStoreName() == null || "".equals(merchantApply.getStoreName())) {
            return false;
        }
        //联系人
        if (merchantApply.getContract() == null || "".equals(merchantApply.getContract())) {
            return false;
        }
        //联系电话
        if (merchantApply.getPhone() == null || "".equals(merchantApply.getPhone())) {
            return false;
        }
        //身份证号码
        if (merchantApply.getIdCard() == null || "".equals(merchantApply.getIdCard())) {
            return false;
        }
        //身份证国徽页
        if (merchantApply.getIdCardFront() == null || "".equals(merchantApply.getIdCardFront())) {
            return false;
        }
        //身份证信息页
        if (merchantApply.getIdCardBack() == null || "".equals(merchantApply.getIdCardBack())) {
            return false;
        }
        //行业id
        if (merchantApply.getIndustryId() == null || "".equals(merchantApply.getIndustryId())) {
            return false;
        }
        //省份id
        if (merchantApply.getProvinceId() == null || "".equals(merchantApply.getProvinceId())) {
            return false;
        }
        //城市id
        if (merchantApply.getCityId() == null || "".equals(merchantApply.getCityId())) {
            return false;
        }
        //区县id
        if (merchantApply.getAreaId() == null || "".equals(merchantApply.getAreaId())) {
            return false;
        }
        //详细地址
        if (merchantApply.getAddress() == null || "".equals(merchantApply.getAddress())) {
            return false;
        }
        //营业执照照片
        if (merchantApply.getBusinessLicenseImg() == null || "".equals(merchantApply.getBusinessLicenseImg())) {
            return false;
        }
        //封面图,门头照
        if (merchantApply.getCoverImage() == null || "".equals(merchantApply.getCoverImage())) {
            return false;
        }
        //店内照
        if (merchantApply.getImages() == null || "".equals(merchantApply.getImages())) {
            return false;
        }
        return true;
    }

    /**
     * 检查实体类是否存在
     *
     * @param merchantApply
     * @return
     */
    public String checkPojo(MerchantApply merchantApply) {
        if (merchantApply == null) {
            return "该条入驻申请不存在";
        }
        if (merchantApply.getDeletedAt() != null) {
            return "该条入驻申请已被删除";
        }
        return "";
    }

}
